//
//  SAHukidashi.m
//  01_kakin
//
//  Created by jon due on 12/03/29.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "SAHukidashi.h"

#define HD_imgFile    @"hukidashi_bg.png"
#define HD_interval   60

#define HD_RectImg    CGRectMake(3,3, 104, 74)
#define Rect_addX       10
#define Rect_addY       20


@implementation SAHukidashi

@synthesize hukidashiImg = _hukidashiImg;
@synthesize mainLabel = _mainLabel;
@synthesize DataAry = _DataAry;
@synthesize insertAry = _insertAry;

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
    }
    return self;
}

- (id)initReloadMode:(CGRect)frame mode:(HDReloadMode)mm
{
    self = [super initWithFrame:frame];
    if (self) {
        
        reloadMode = mm;
        
        self.DataAry = [[ NSArray alloc ]initWithObjects:@"法務省は２９日、東京・広島・福岡",@"2.SUPER JUNIOR DONGHAE & EUNHYUK「Oppa,Oppa」は、2012年4月4日発売の最新曲シングル。", nil];
    }
    return self;
}


-(void)dealloc{
    [ _hukidashiImg release ];
    [ _mainLabel release ];
    [ _DataAry release ];
    [ _insertAry release ];
    [ super dealloc ];
}

-(void)setObject{
    // 初期化
    lastFileNo = 0;
    lastSoundFileNo = -1;
    
    self.insertAry = [[ NSMutableArray alloc ]init];
    
    self.backgroundColor = [ UIColor clearColor ];
    
    // 背景セット
    self.hukidashiImg = [[ UIImageView alloc ]initWithFrame:HD_RectImg];
    self.hukidashiImg.image = [ UIImage imageNamed:HD_imgFile ];
    [ self addSubview:self.hukidashiImg ];
    
    // レベルセット
    self.mainLabel = [[ UILabel alloc ]initWithFrame:self.frame];
    self.mainLabel.font = [ UIFont systemFontOfSize:15 ];
    self.mainLabel.backgroundColor = [ UIColor clearColor ];
    self.mainLabel.numberOfLines = 0;
    self.mainLabel.lineBreakMode = UILineBreakModeWordWrap;
    [ self addSubview:self.mainLabel ];
    
    // 隠す
    self.alpha = 0.0;
    
    // DBチェック
    BOOL isNetWork = YES;
    if([ API_MESSAGE length ] < 1){
        [ self getHukidashiData ];
    }
}


// データの取得
-(void)getHukidashiData{
    
    // 通信状況のチェック後
    // メッセージバージョン確認後
    
    
    // api
    NSURL *url = [ NSURL URLWithString:API_MESSAGE ];
    
    //postメソッド
    ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
    [request setRequestMethod:@"POST"];
    [ request addRequestHeader:@"Content-Type" value:@"application/json" ];
    [ request addRequestHeader:@"Accept" value:@"application/json" ];
    
//    [ request setPostValue:@"bs.test0002@gmail.com" forKey:@"id"];
//    [ request setPostValue:@"bravesoft" forKey:@"pass"];
    
    request.delegate = self;
    //[request setDefaultResponseEncoding:NSUTF8StringEncoding];
    [request startAsynchronous];
}

// つぶやきの行数を計算する
-(CGSize)lineCalculation :(NSString*)str{
    
    CGRect rect = self.frame;
    
	CGSize Tsize = [str 
                    sizeWithFont:self.mainLabel.font  
                    constrainedToSize:CGSizeMake(rect.size.width - (Rect_addX + Rect_addY), 9999) 
                    lineBreakMode:UILineBreakModeWordWrap];

    return Tsize;
}

// つぶやく
-(void)startHukidashi{
    
    // ランダムっぽい処理
    int ran = arc4random()%[ self.DataAry count ];
    
    while (lastSoundFileNo == ran) {
        ran = arc4random()%[ self.DataAry count ];
    }
    
    NSString *selectMes = [ self.DataAry objectAtIndex:ran];
    
    // 表示文言ラベルのサイズを測る
    CGSize size = [ self lineCalculation:selectMes ];
    
    // ラベルの高さを計算してセット
    CGRect rect = self.frame;
    rect.size = size;
    rect.size.height = rect.size.height + (Rect_addX + Rect_addY) + 40;
    
    //計算したサイズをviewにセット
    self.frame = rect;
    self.hukidashiImg.frame = CGRectMake(0, 0, rect.size.width, rect.size.height );
    
    // labelにセットする
    self.mainLabel.frame = CGRectMake(Rect_addX,Rect_addY, size.width, size.height);
    self.mainLabel.text = selectMes;
    
    self.alpha = 1.0;

}

/*=== 吹き出しを消す ===*/
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    self.alpha = 0.0;
    
    if(reloadMode == HDReloadModeAuto){
        // 次のを出す処理
        [ self performSelector:@selector(startHukidashi) withObject:self afterDelay:HD_interval ];
    }
}


// データの削除・更新
-(void)updateHukidashi{
    
    messageClient *client = [[ messageClient alloc ]init];
    
    // データ保存
    for(int i = 0;i < [ self.insertAry count ];i++){
        messageBean *bean = [ self.insertAry objectAtIndex:i ];
        [ client insertMessage:bean ];
    }
    
    [ client release ];
}

/* ============================================================================== */
#pragma mark - ASIHTTPRequestDelegate
/* ============================================================================== */

// 成功時のdelegate
- (void)requestFinished:(ASIHTTPRequest *)request{
    
    // API
    NSString *JsonStr = [ request responseString ];
    
    if([ JsonStr length ] < 1){
        return;
    }
    
    // パース
    NSArray *responsAry = [JsonStr objectFromJSONString];
    
    // Beanに突っ込む
    for (int i = 0; i < [ responsAry count ]; i++) {
        NSDictionary *dic = [ responsAry objectAtIndex:i ];
        
        messageBean *bean = [[ messageBean alloc]init ];
        bean.No = [[ dic objectForKey:@"no" ] intValue];
        bean.version = [ dic objectForKey:@"version" ];
        bean.message = [ dic objectForKey:@"message" ];
        
        // DB用保存ary
        [self.insertAry addObject:bean ];
        NSLog(@"Success = %@",[ dic objectForKey:@"Success" ]);
        [ bean release ];
    }
}

// 失敗時のdelegate
- (void)requestFailed:(ASIHTTPRequest *)request{
    NSLog(@"えらー");
    
}

@end
